package com.kuqi.blog.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kuqi.blog.dao.mapper.ArticleMapper;
import com.kuqi.blog.dao.pojo.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author:kuqi
 * @createTime:2021/12/16 15:52
 * @description:
 *      线程池逻辑层
 */

@Component  //spring注解，用于管理实例类；IOC控制反转的实现
public class ThreadService {
    //期望此操作在线程池执行不会影响原有的主线程
    //线程池相关知识在JUC并发编程有所讲解
    @Async("taskExecutor")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article){
        Integer viewCounts = article.getViewCounts();
        Article articleUpdate = new Article();
        articleUpdate.setViewCounts(viewCounts+1);
        //update article set view_count=100 where view_count=99 and id=1
        //更新条件带了view_count是为了怕其他线程以及将其修改，这样可以避免重复修改
        LambdaQueryWrapper<Article> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(Article::getId,article.getId());
        updateWrapper.eq(Article::getViewCounts,viewCounts);
        articleMapper.update(articleUpdate,updateWrapper);

        try {
            Thread.sleep(3000);
            System.out.println("更新完成了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
